﻿using System.Collections.Generic;
using System.Web.Mvc;

namespace TY.UI.Mvc
{
    /// <summary>
    /// 全局action权限拦截过滤器
    /// </summary>
    public class WebAuthorityAttribute : ActionFilterAttribute
    {
        //免拦截的action名称
        public static List<string> List = new List<string> { "LogIn", "LogOn", "GetImgCode" };
        /// <summary>
        /// 在执行操作方法之前由 ASP.NET MVC 框架调用。
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if(List.Contains(filterContext.ActionDescriptor.ActionName))
                return;
            //用户有登录信息，不拦截
            if (filterContext.HttpContext.Session == null || filterContext.HttpContext.Session["UserName"] != null)
                return;
            if (filterContext.HttpContext.Request.IsAjaxRequest())
                filterContext.Result = new HttpStatusCodeResult(401,"登录过期，请重新登录");
            else
            //跳转到登录页
            filterContext.Result = new RedirectResult("~/home/LogIn?state=0");
        }
    }
}